import datetime
import os

import requests


# from Wallpaper.models import Wallpaper, Category


class AiBiZhiWallpaperSpider:
    def __init__(self):
        self.classes = {
            '美女': '4e4d610cdf714d2966000000', '动漫': '4e4d610cdf714d2966000003', '风景': '4e4d610cdf714d2966000002',
            '游戏': '4e4d610cdf714d2966000007', '文字': '5109e04e48d5b9364ae9ac45', '视觉': '4fb479f75ba1c65561000027',
            '情感': '4ef0a35c0569795756000000', '设计': '4fb47a195ba1c60ca5000222', '明星': '5109e05248d5b9368bb559dc',
            '物语': '4fb47a465ba1c65561000028', '男人': '4e4d610cdf714d2966000006', '机械': '4e4d610cdf714d2966000005',
            '城市': '4fb47a305ba1c60ca5000223', '动物': '4e4d610cdf714d2966000001'
        }
        self.categories = self.classes.keys()
        self.headers = {
            "UserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0",
        }

    def main(self, category):
        page = 1
        while True:
            print(f"{category} 第 {page} 页")
            url = f"http://service.picasso.adesk.com/v1/vertical/category/{self.classes.get(category)}/vertical?limit=30&adult=false&first=1&order=hot&skip={(page - 1) * 30}"
            req = requests.get(url, headers=self.headers).json()
            datasets = req['res']['vertical']
            if datasets != [] and datasets is not None:
                for data in datasets:
                    # title = tag = "".join(data['tag'])
                    # dt = datetime.datetime.fromtimestamp(data['atime'])
                    src = data['wp']
                    id = data['id']
                    uri = f"/media/staticwallpaper/vertical/{id}.jpg"
                    path = f'E:/Android/Service/MyStation/static{uri}'
                    if not os.path.exists(path):
                        print(src)
                        with open(path, 'wb') as fp:
                            fp.write(requests.get(src).content)
                    # try:
                    #     category_ = Category.objects.get(name=category)
                    # except:
                    #     category_ = Category(name=category)
                    #     category_.save()
                    # try:
                    #     wallpaper = Wallpaper(title=title, category=category_, tag=tag, url=uri, create_time=dt)
                    #     wallpaper.save()
                    # except:
                    #     print("已存在")
                page += 1
            else:
                # print(f"共{page}页")
                break


if __name__ == "__main__":
    spider = AiBiZhiWallpaperSpider()
    for i in spider.categories:
        spider.main(i)
